﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;

namespace scmsByAspdNet.cotro.student {
  /// <summary>
  /// unChooseCourse1 的摘要说明
  /// </summary>
  public class unChooseCourse1 : IHttpHandler {

    public void ProcessRequest(HttpContext context) {
      context.Response.ContentType = "text/plain";

      //获取参数
      string stu_id = context.Request["stu_id"];
      //数据库
      SqlConnection conn = new SqlConnection("Data Source=106.54.69.143;database=scms;uid=sa;pwd=Aspdotnet666");
      conn.Open();

      SqlCommand sql_rows = new SqlCommand($"SELECT sc.id,st.name,sc.title,sc.credit,sc.hour,sc.attribute,sc.proportion,sc.faculty,sc.comment,sc.cover FROM sc_course sc,sc_teacher st,sc_cour_tea sct WHERE sc.id NOT IN(SELECT scs.cour_id FROM sc_student ss,sc_cour_stu scs WHERE scs.stu_id=ss.id AND ss.id={stu_id}) AND sc.id=sct.cour_id AND sct.tea_id=st.id", conn);
      string rows = "[";
      SqlDataReader reader = sql_rows.ExecuteReader();
      for (; reader.Read();) {
        rows += $"{{\"cour_id\":\"{reader[0].ToString()}\",\"teache_name\":\"{reader[1].ToString()}\",\"title\":\"{reader[2].ToString()}\",\"credit\":\"{reader[3].ToString()}\",\"hour\":\"{reader[4].ToString()}\",\"attribute\":\"{reader[5].ToString()}\",\"proportion\":\"{reader[6].ToString()}\",\"faculty\":\"{reader[6].ToString()}\",\"comment\":\"{reader[6].ToString()}\",\"cover\":\"{reader[6].ToString()}\"}},";
      }
      rows = rows.Substring(0, rows.Length - 1);
      rows += "]";
      reader.Close();
      //获取行数-----
      SqlCommand sql_total = new SqlCommand($"SELECT count(sc.id) FROM sc_course sc,sc_teacher st,sc_cour_tea sct WHERE sc.id NOT IN(SELECT scs.cour_id FROM sc_student ss,sc_cour_stu scs WHERE scs.stu_id=ss.id AND ss.id={stu_id}) AND sc.id=sct.cour_id AND sct.tea_id=st.id", conn);
      string total = "";
      reader = sql_total.ExecuteReader();
      if (reader.Read()) {
        total = reader[0].ToString();
      }
      else {
        total = "0";
      }
      reader.Close();
      conn.Close();
      //返回数据
      string ret = "{" +
        "\"total\":\"" + total + "\"," +
        "\"rows\":" + rows + "" +
        "}";
      System.Console.WriteLine(ret);
      context.Response.StatusCode = 200;
      context.Response.Write(ret);
    }

    public bool IsReusable {
      get {
        return false;
      }
    }
  }
}